<?php 
namespace app\api\controller;

use think\Controller;
use think\facade\Validate;
use think\Db;

/**
 * @title 我的接口
 */
class My extends Controller
{
	/**
	 * @title 检测是否登录
	 * @description 检测是否登录
	 * @url /api/checkLogin
	 * @method post
	 *
	 */
	public function checkLogin()
	{
		$user_id = cookie('user_id');

		if($user_id){
			$userinfo = Model('User')::get($user_id);
			if($userinfo->status == 0){
				$this->result('',2,'该用户已经被禁用','json');
			}
			$this->result('',1,'正在登录','json');
		}else{
			$this->result('',0,'已经退出','json');
		}
	}

	public function checkVersion()
	{
		$res = model('System')::get(1);

		if($res){
			$this->result(['android_version'=>$res->android_version,'android_url'=>$res->android_url,'ios_version'=>$res->ios_version,'ios_url'=>$res->ios_url],1,'获取成功','json');
		}else{
			$this->result('',0,'获取失败','json');
		}
	}

	/**
	 * @title 用户信息
	 * @description 用户信息
	 * @url /api/userinfo
	 * @method post
	 *
	 * @return data:返回数据@
	 * @data user_id:用户id;username:用户昵称;avatar:头像
	 * 
	 */
	public function userinfo()
	{
		$user_id = cookie('user_id');

		$userinfo = model('User')::get($user_id)->withAttr('avatar',function($value,$data){
			return path_deal_with($value);
		});

		$this->result(['user_id'=>$userinfo->id,'username'=>$userinfo->username,'avatar'=>$userinfo->avatar],1,'获取成功','json');
	}

	/**
	 * @title 修改头像
	 * @description 修改头像
	 * @url /api/change_avatar
	 * @method post
	 *
	 * @param name:avatar type:file require:1 desc:头像
	 * 
	 */
	public function change_avatar()
	{
		$user_id = cookie('user_id');

		$avatar = request()->file('avatar');
		$data = [];

		if(!empty($avatar)){
			$data['avatar'] = upload_image($avatar,'avatar');
		}else{
			$this->result('',0,'请上传头像','json');
		}

		$res = model('User')->save($data,['id'=>$user_id]);
		if($res){
			$this->result(['avatar'=>$data['avatar']],1,'修改成功','json');
		}else{
			$this->result('',0,'修改失败','json');
		}
	}

	/**
	 * @title 修改昵称
	 * @description 修改昵称
	 * @url /api/change_username
	 * @method post
	 *
	 * @param name:username type:string require:1 desc:昵称
	 * 
	 */
	public function change_username()
	{
		$user_id = cookie('user_id');

		$username = trim(input('username'));

		if(!$username){
			$this->result('',0,'请输入昵称','json');
		}

		$res = model('User')->save(['username'=>$username],['id'=>$user_id]);
		if($res){
			$this->result('',1,'修改成功','json');
		}else{
			$this->result('',0,'修改失败','json');
		}
	}
	
	/**
	 * @title 修改密码
	 * @description 修改密码
	 * @url /api/change_password
	 * @method post
	 *
	 * @param name:phone type:string require:1 desc:手机号
	 * @param name:captcha type:string require:1 desc:验证码
	 * @param name:password type:string require:1 desc:密码
	 * @param name:check_password type:string require:1 desc:确认密码
	 * 
	 */
	public function change_password()
	{
		$user_id = cookie('user_id');

		$data = [
			'phone' => trim(input('phone')),
			'captcha' => trim(input('captcha')),
			'password' => trim(input('password')),
			'check_password' => trim(input('check_password'))
		];

		$rule = [
			'phone' => 'require|mobile',
			'captcha' => 'require',
			'password' => 'require|alphaNum|length:6,12',
			'check_password' => 'require|alphaNum|length:6,12'
		];

		$msg = [
			'phone.require' => '请输入手机号',
			'phone.mobile' => '手机号格式不正确',
			'captcha.require' => '请输入验证码',
			'password.require' => '请输入新密码',
			'password.alphaNum' => '新密码为6-12位数字和字母的组合',
			'password.length' => '新密码为6-12位数字和字母的组合',
			'check_password.require' => '请输入确认密码',
			'check_password.alphaNum' => '确认密码密码为6-12位数字和字母的组合',
			'check_password.length' => '确认密码密码为6-12位数字和字母的组合'
		];

		$validate = Validate::make($rule,$msg);
		if(!$validate->check($data)){
			$this->result('',0,$validate->getError(),'json');
		}

		//验证验证码
		if($data['captcha'] != cache('captcha'.$data['phone'])){
			$this->result('',0,'验证码不正确','json');
		}else{
			cache('captcha'.$data['phone'],null,0);
		}
		//验证密码一致性
		if($data['password'] != $data['check_password']){
			$this->result('',0,'两次密码不一致','json');
		}

		$res = model('User')->save(['password'=>md5($data['password'])],['id'=>$user_id]);
		if($res){
			$this->result('',1,'修改成功','json');
		}else{
			$this->result('',0,'修改失败','json');
		}

	}

	/**
	 * @title 实名认证
	 * @description 实名认证
	 * @url /api/real
	 * @method post
	 *
	 * @param name:realname type:string require:1 desc:姓名
	 * @param name:identify_num type:string require:1 desc:身份证号
	 * @param name:identify_font type:file require:1 desc:身份证正面
	 * @param name:identify_back type:file require:1 desc:身份证反面
	 * 
	 */
	public function real()
	{
		$user_id = cookie('user_id');

		$data = [
			'realname' => trim(input('realname')),
			'identify_num' => trim(input('identify_num')),
			'identify_font' => request()->file('identify_font'),
			'identify_back' => request()->file('identify_back')
		];

		$rule = [
			'realname' => 'require',
			'identify_num' => 'require|idCard',
			'identify_font' => 'require',
			'identify_back' => 'require'
		];

		$msg = [
			'realname.require' => '请输入姓名',
			'identify_num.require' => '请输入身份证号',
			'identify_num.idCard' => '身份证号格式不正确',
			'identify_font.require' => '请上传身份证正面照',
			'identify_back.require' => '请上传身份证反面照',
		];

		$validate = Validate::make($rule,$msg);
		if(!$validate->check($data)){
			$this->result('',0,$validate->getError(),'json');
		}

		$data['identify_font'] = upload_image($data['identify_font'],'dentify');
		$data['identify_back'] = upload_image($data['identify_back'],'dentify');
		$data['is_real'] = 1;

		$res = model("User")->save($data,['id'=>$user_id]);
		if($res){
			$this->result('',1,'认证提交成功','json');
		}else{
			$this->result('',0,'认证提交失败','json');
		}
	}

	/**
	 * @title 我的发布
	 * @description 我的发布
	 * @url /api/my_release
	 * @method post
	 *
	 * @return data:返回数据@
	 * @data id:发布id;type:分布类型;title:标题;price:价格;brand_id:品牌id;model_id:车型id;car_img:图片;car_brand:品牌名称;car_model:车型名称
	 * 
	 */
	public function my_release()
	{
		$user_id = cookie('user_id');

		$map[] = ['user_id','=',$user_id];

		$res = model('Car')
			->field('id,type,title,price,price_type,brand_id,model_id')
			->withAttr('type',function($value,$data){
				return $value == 1 ? '售卖' : '求购';
			})
			->withAttr('price_type',function($value,$data){
				return $value == 1 ? '内' : '起';
			})
			->withAttr('car_img',function($value,$data){
				$car_img = model('CarImg')->where('car_id',$data['id'])->find();
				return $car_img ? path_deal_with($car_img->image) : '';
			})
			->withAttr('car_brand',function($value,$data){
				return model('CarBrand')->where('id',$data['brand_id'])->value('brand_name');
			})
			->withAttr('car_model',function($value,$data){
				return model('CarModel')->where('id',$data['model_id'])->value('model_name');
			})
			->where($map)
			->order('create_time desc')
			->append(['car_img','car_brand','car_model'])
			->paginate(10,false,['query'=>input()]);

		$this->result(['data'=>$res->items(),'total'=>$res->total()],1,'获取成功','json');
	}

	/**
	 * @title 发布详情
	 * @description 发布详情
	 * @url /api/release_detail
	 * @method post
	 *
	 * @param name:car_id type:integer require:1 desc:发布id
	 *
	 * @return data:返回数据@
	 * @data id:发布id;type:分布类型;title:标题;price:价格;brand_id:品牌id;model_id:车型id;brief:详情;create_time:发布时间;car_img:图片;car_brand:品牌名称;car_model:车型名称;release_num:发布数量;userinfo:用户信息
	 * 
	 */
	public function release_detail()
	{
		$car_id = (int)input('car_id',0);
		if(!$car_id){
			$this->result('',0,'参数错误','json');
		}

		$map[] = ['id','=',$car_id];

		$res = model('Car')
			->field('id,user_id,type,title,price,price_type,brand_id,model_id,brief,create_time')
			->withAttr('type',function($value,$data){
				return $value == 1 ? '售卖' : '求购';
			})
			->withAttr('price_type',function($value,$data){
				return $value == 1 ? '内' : '起';
			})
			->withAttr('car_img',function($value,$data){
				$car_img = model('CarImg')->where('car_id',$data['id'])->column('image');
				foreach ($car_img as $key => $val) {
					$car_img[$key] = path_deal_with($val);
				}
				return $car_img;
			})
			->withAttr('car_brand',function($value,$data){
				return model('CarBrand')->where('id',$data['brand_id'])->value('brand_name');
			})
			->withAttr('car_model',function($value,$data){
				return model('CarModel')->where('id',$data['model_id'])->value('model_name');
			})
			->withAttr('release_num',function($value,$data) {
				return model('Car')->where('user_id',$data['user_id'])->count();
			})
			->withAttr('userinfo',function($value,$data) {
				$userinfo = model('User')->field('username,realname,id as user_id,avatar')
							->withAttr('avatar',function($val,$result){
								return path_deal_with($val);
							})
							->where('id',$data['user_id'])->find();

				return $userinfo;
			})
			->where($map)
			->order('create_time desc')
			->append(['car_img','car_brand','car_model','release_num','userinfo'])
			->find();

		$this->result(['data'=>$res],1,'获取成功','json');

	}

	/**
	 * @title 编辑发布
	 * @description 编辑发布
	 * @url /api/release_edit
	 * @method post
	 *
	 * @param name:car_id type:integer require:1 desc:发布id
	 * @param name:type type:integer require:1 desc:分布类型;1=售卖，2=求购
	 * @param name:title type:string require:1 desc:标题
	 * @param name:price type:string require:1 desc:价格
	 * @param name:price_type type:string require:0 desc:价格类型：1=内，2=起
	 * @param name:brief type:string require:1 desc:详情
	 * @param name:car_img[] type:file require:1 desc:图片
	 * @param name:brand_id type:integer require:0 desc:品牌id
	 * @param name:model_id type:integer require:0 desc:车型id
	 *
	 */
	public function release_edit()
	{
		$user_id = cookie('user_id');

		$data = [
			'car_id' => input('car_id'),
			'type' => input('type',1),
			'title' => input('title'),
			'price' => input('price'),
			'brief' => input('brief'),
			'car_img' => request()->file('car_img')
		];

		if($data['type'] == 1){
			$data['brand_id'] = input('brand_id');
			$data['model_id'] = input('model_id');
		}else{
			$data['price_type'] = input('price_type',1);
		}

		$rule = [
			'car_id' => 'require',
			'type' => 'require',
			'title' => 'require',
			'price' => 'require',
			'brief' => 'require',
			'car_img' => 'require'
		];

		if($data['type'] == 1){
			$rule['brand_id'] = 'require';
			$rule['model_id'] = 'require';
		}else{
			$rule['price_type'] = 'require';
		}

		$msg = [
			'car_id.require' => '参数错误',
			'type.require' => '请选择发布类型',
			'title.require' => '请输入标题',
			'price.require' => '请输入价格',
			'brief.require' => '请输入详情',
			'car_img.require' => '请上传图片'
		];

		if($data['type'] == 1){
			$msg['brand_id.require'] = '请选择品牌';
			$msg['model_id.require'] = '请选择车型';
		}else{
			$msg['price_type.require'] = '请选择价格类型';
		}

		$validate = Validate::make($rule,$msg);
		if(!$validate->check($data)){
			$this->result('',0,$validate->getError(),'json');
		}

		$car_img = $data['car_img'];
		unset($data['car_img']);

		Db::startTrans();
		try{
			model('Car')->save($data,['id'=>$data['car_id']]);

			if($car_img){
				foreach ($car_img as $key => $value) {
					$car_img_data[$key] = [
						'car_id' => $data['car_id'],
						'image' => upload_image($value)
					];
				}

				model("CarImg")->saveAll($car_img_data);
			}
			Db::commit();
		}catch(\Exception $e){
			Db::rollback();
			$this->result('',0,'编辑失败','json');
		}

		$this->result('',1,'编辑成功','json');

	}

	/**
	 * @title 意见反馈
	 * @description 意见反馈
	 * @url /api/feedback
	 * @method post
	 *
	 * @param name:content type:string require:1 desc:反馈内容
	 * 
	 */
	public function feedback()
	{
		$user_id = cookie('user_id');

		$content = trim(input('content'));
		if(!$content){
			$this->result('',0,'请输入反馈内容','json');
		}

		$res = model('Feedback')->save(['user_id'=>$user_id,'content'=>$content]);
		if($res){
			$this->result('',1,'提交成功','json');
		}else{
			$this->result('',0,'提交失败','json');
		}
	}

	/**
	 * @title 联系客服
	 * @description 联系客服
	 * @url /api/kefu
	 * @method post
	 *
	 */
	public function kefu()
	{
		$res = model("System")::get(1);

		$this->result(['kefu'=>$res->phone],1,'获取成功','json');
	}

	/**
	 * @title logo
	 * @description logo
	 * @url /api/logo
	 * @method post
	 *
	 */
	public function logo()
	{
		$res = model("System")::get(1);

		$this->result(['logo'=>path_deal_with($res->logo)],1,'获取成功','json');
	}

}

?>